<template>
  <section class="todoapp">
    <TodoHeader @hadd="hadd"></TodoHeader>
    <TodoMain :list="showList" @hdel="hdel" @hchange="hchange" @changeAll = changeAll></TodoMain>
    <TodoFooter :list="showList" @hdeldesk="hdeldesk" @changetype="hchangetype"></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list:JSON.parse(localStorage.getItem('list')),
      type:'all'
    }
  },
  methods:{
    hdel(id) {
      const index = this.list.findIndex(item => item.id === id)
      this.list.splice(index,1)
    },
    hchange(id) {
      const obj = this.list.find(item => item.id === id)
      obj.isDone = !obj.isDone
    },
    hadd(msg) {
      this.list.push({
        name:msg,
        isDone:false,
        id:Date.now()
      })
    },
    hdeldesk() {
      this.list = this.list.filter(item => !item.isDone)
    },
    hchangetype(type) {
      this.type = type
      console.log(this.type);
    },
    changeAll(val) {
      this.list.forEach(item => item.isDone = val)
    }
  },
  computed:{
    showList() {
      if(this.type === 'all') {
        return this.list
      } else if (this.type === 'active') {
        return this.list.filter(item => !item.isDone)
      } else if (this.type === 'completed') {
        return this.list.filter(item => item.isDone)
      }
    }
  },
  watch:{
    list:{
      deep:true,
      handler() {
        localStorage.setItem('list',JSON.stringify(this.list))
      }
    }
  }
};
</script>

<style></style>
